package com.zj.service;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;

@Configuration
@Service
public class ToolService {
    @Tool("求一个字符串的长度")
    int strLength(String str){
        System.out.println("求一个字符串的长度\""+str+"\"");
        return str.length();
    }

    //        @Tool("求任意多个数的和")
    int add(int... nums){
        System.out.println("求任意多个数的和");
        int sum=0;
        for(int num:nums){
            sum+=num;
        }
        System.out.println("任意多个数的和为："+sum);
        return sum;
    }

    //        @Tool("计算一个数的平方根")
    double sqrt(int num){
        double sqrt=Math.sqrt(num);
        System.out.println("计算一个数的平方根"+num+"的平方根为："+sqrt);
        return sqrt;
    }
    ///////////////////////////////以下是天气相关的AI/////////////////////////////////////////////////
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class WeatherResponse{
        @JsonProperty("results")
        public List<WeatherData> results;

        @JsonIgnoreProperties(ignoreUnknown = true)
        public static class WeatherData{
            @JsonProperty("location")
            @JsonIgnoreProperties(ignoreUnknown = true)
            public Location location;
            @JsonProperty("now")
            @JsonIgnoreProperties(ignoreUnknown = true)
            public Now now;
            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class Location{
                @JsonProperty("name")
                public String name;
                //其他字段会被自动忽略
            }
            @JsonIgnoreProperties(ignoreUnknown = true)
            public static class Now{
                @JsonProperty("text")
                public String text;
                @JsonProperty("temperature")
                public String temperature;
                @JsonProperty("code")//新增code字段
                public String code;//虽然不适用但需要定义

            }
        }
    }
    //温度单位的枚举类型
    public enum TemperatureUnit{
        CELSIUS,FAHRENHEIT,KELVIN;
    }

    @Tool("用户会询问某个城市的天气，他还会告诉你温度的显示单位,请返回指定城市的天气情况")
    public String getWeather(
            @P("城市名称") String city,
            @P("温度单位") TemperatureUnit unit){
        try{
            String apiKey=System.getenv("WEATHER_API_KEY");
            System.out.println(apiKey);
            String unitStr=unit.name().toLowerCase().charAt(0)+"";
            String url=String.format("https://api.seniverse.com/v3/weather/now.json?key=%s&location=%s&language=zh-Hans&unit=%s",
                    apiKey, URLEncoder.encode(city,"UTF-8"),unitStr);

            //构建一个客户端
            HttpClient client=HttpClient.newHttpClient();
            //构建一个请求
            HttpRequest request=HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .timeout(Duration.ofSeconds(10))
                    .build();
            HttpResponse<String> response=client.send(request, HttpResponse.BodyHandlers.ofString());
            String json=response.body();

            ObjectMapper mapper=new ObjectMapper();
            WeatherResponse weatherResponse=mapper.readValue(json, WeatherResponse.class);
            WeatherResponse.WeatherData.Now now=weatherResponse.results.get(0).now;
            return String.format("%s的天气：%s:天气 %s C",city,now.text,now.temperature);
        }catch (Exception e){
            e.printStackTrace();
            return "获取天气信息失败"+e.getMessage();
        }
    }
}
//使用工具 大模型会自动调用工具类的方法
//没有工具的情况下，大模型会直接回答用户的问题，不会调用工具类的方法


